﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Synchronization;
using Medianamik.UI.Controls;
using Medianamik.UI.Web.Shop.Data.Repositories;
using StructureMap;

namespace Medianamik.UI.Web.Shop
{
    public partial class ShopCompanyEdit : BaseModuleEditionPage<NodeWrapper>
    {
        private readonly AddressRecordRepository _addressRecordRepository =
            ObjectFactory.GetInstance<AddressRecordRepository>();

        protected override void Save(object sender, EventArgs e)
        {
            Page.Validate(BaseMedianamikControl.DefaultValidationGroupName);
            if (IsValid)
            {
                NodeManager.SaveNode(MedianamikFormTemplate.GetFormValue(CurrentNode));

                var records = Addresses.DataSource;

                foreach (var record in records)
                {
                    record.DefaultCultureName = "";

                    foreach (var property in record.Properties)
                    {
                        property.CultureName = "";
                    }
                }
                var nodeSynchronizer = new NodeSynchronizer();
                IList<Node> nodes;
                if(nodeSynchronizer.Synchronize(records, out nodes))
                {
                    NodeManager.SaveNodes(nodes, true);
                }

                Addresses.DataSource = Addresses.DataSource
                    .Where(r => r.SynchronizeAction != SynchronizeActions.Delete &&
                                r.SynchronizeAction != SynchronizeActions.DeleteBranch).ToArray();

                Response.Redirect(ReturnURL);
            }
        }   

        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                Addresses.DataSource = ((CurrentNode != null)
                                            ? _addressRecordRepository.GetAddresses(CurrentNode.ID)
                                            : Enumerable.Empty<Record>()).ToArray();

                Addresses.DataBind();
            }
            base.OnLoad(e);
        }

        public override LinkButton SaveButton
        {
            get { return SaveLinkButton; }
        }

        public override MedianamikFormTemplate MedianamikFormTemplate
        {
            get { return Fields; }
        }

        protected override string TypeIdParamName
        {
            get
            {
                return DefaultParamNames.TypeID;
            }
        }

        protected override string ParentNodeIdParamName
        {
            get
            {
                return DefaultParamNames.ParentNodeID;
            }
        }
    }
}
